import axios from 'axios';
import { KycAPITester } from './kyc-api-test';

const BASE_URL = 'http://localhost:3000';

interface TestResult {
    success: boolean;
    message: string;
    data?: any;
}

class I18nTester {
    private baseURL: string;

    constructor(baseURL: string) {
        this.baseURL = baseURL;
    }

    /**
     * 测试认证接口的多语言支持
     */
    async testAuthI18n(): Promise<void> {
        console.log('🌍 测试认证接口多语言支持...\n');

        // 测试英文
        console.log('📝 测试英文 (en):');
        await this.testWalletLogin('en');

        // 测试中文
        console.log('\n📝 测试中文 (zh):');
        await this.testWalletLogin('zh');

        // 测试默认语言
        console.log('\n📝 测试默认语言 (无参数):');
        await this.testWalletLogin();
    }

    /**
     * 测试钱包登录
     */
    private async testWalletLogin(lang?: string): Promise<void> {
        try {
            const url = lang ? `${this.baseURL}/auth/wallet-login?lang=${lang}` : `${this.baseURL}/auth/wallet-login`;

            const response = await axios.post(url, {
                walletAddress: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
                message: 'Test message for i18n',
                signature: '0x1234567890abcdef',
                chainId: 1,
                fullName: 'Test User'
            });

            console.log(`  状态码: ${response.status}`);
            console.log(`  响应语言: ${response.headers['content-language'] || '未设置'}`);
            console.log(`  成功消息: ${response.data.message}`);
            console.log(`  数据: ${JSON.stringify(response.data.data, null, 2)}`);
        } catch (error: any) {
            if (error.response) {
                console.log(`  错误状态码: ${error.response.status}`);
                console.log(`  错误消息: ${error.response.data?.message || error.message}`);
            } else {
                console.log(`  网络错误: ${error.message}`);
            }
        }
    }

    /**
     * 测试 KYC 接口的多语言支持
     */
    async testKycI18n(): Promise<void> {
        console.log('\n🌍 测试 KYC 接口多语言支持...\n');

        // 首先进行认证获取 JWT token
        const token = await this.authenticateWallet();
        if (!token) {
            console.log('❌ 无法获取认证令牌，跳过 KYC 测试');
            return;
        }

        const headers = {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        };

        // 测试英文
        console.log('📝 测试英文 (en):');
        await this.testKycEndpoints(headers, 'en');

        // 测试中文
        console.log('\n📝 测试中文 (zh):');
        await this.testKycEndpoints(headers, 'zh');
    }

    /**
     * 认证钱包获取 JWT token
     */
    private async authenticateWallet(): Promise<string | null> {
        try {
            const response = await axios.post(`${this.baseURL}/auth/wallet-login`, {
                walletAddress: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
                message: 'Test message for i18n',
                signature: '0x1234567890abcdef',
                chainId: 1,
                fullName: 'Test User'
            });

            return response.data.data?.access_token || null;
        } catch (error) {
            console.log('认证失败:', error);
            return null;
        }
    }

    /**
     * 测试 KYC 端点
     */
    private async testKycEndpoints(headers: any, lang: string): Promise<void> {
        const langParam = `?lang=${lang}`;

        // 测试生成 token
        try {
            const response = await axios.post(`${this.baseURL}/kyc/token${langParam}`, {}, { headers });
            console.log(`  KYC Token 生成: ${response.data.message}`);
        } catch (error: any) {
            console.log(`  KYC Token 生成失败: ${error.response?.data?.message || error.message}`);
        }

        // 测试获取状态
        try {
            const response = await axios.get(`${this.baseURL}/kyc/status${langParam}`, { headers });
            console.log(`  KYC 状态获取: ${response.data.message}`);
        } catch (error: any) {
            console.log(`  KYC 状态获取失败: ${error.response?.data?.message || error.message}`);
        }
    }

    /**
     * 测试语言检测中间件
     */
    async testLanguageDetection(): Promise<void> {
        console.log('\n🌍 测试语言检测中间件...\n');

        // 测试 Accept-Language 头
        console.log('📝 测试 Accept-Language 头:');
        await this.testWithAcceptLanguage('zh-CN,zh;q=0.9,en;q=0.8');
        await this.testWithAcceptLanguage('en-US,en;q=0.9');

        // 测试查询参数
        console.log('\n📝 测试查询参数:');
        await this.testWithQueryParam('zh');
        await this.testWithQueryParam('en');
    }

    /**
     * 使用 Accept-Language 头测试
     */
    private async testWithAcceptLanguage(acceptLanguage: string): Promise<void> {
        try {
            const response = await axios.post(`${this.baseURL}/auth/wallet-login`, {
                walletAddress: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
                message: 'Test message',
                signature: '0x1234567890abcdef',
                chainId: 1
            }, {
                headers: {
                    'Accept-Language': acceptLanguage
                }
            });

            console.log(`  Accept-Language: ${acceptLanguage}`);
            console.log(`  响应语言: ${response.headers['content-language']}`);
            console.log(`  消息: ${response.data.message}`);
        } catch (error: any) {
            console.log(`  Accept-Language: ${acceptLanguage} - 错误: ${error.response?.data?.message || error.message}`);
        }
    }

    /**
     * 使用查询参数测试
     */
    private async testWithQueryParam(lang: string): Promise<void> {
        try {
            const response = await axios.post(`${this.baseURL}/auth/wallet-login?lang=${lang}`, {
                walletAddress: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
                message: 'Test message',
                signature: '0x1234567890abcdef',
                chainId: 1
            });

            console.log(`  查询参数: lang=${lang}`);
            console.log(`  响应语言: ${response.headers['content-language']}`);
            console.log(`  消息: ${response.data.message}`);
        } catch (error: any) {
            console.log(`  查询参数: lang=${lang} - 错误: ${error.response?.data?.message || error.message}`);
        }
    }

    /**
     * 运行所有测试
     */
    async runAllTests(): Promise<void> {
        console.log('🚀 开始 i18n 多语言测试...\n');
        console.log('='.repeat(50));

        try {
            await this.testAuthI18n();
            await this.testKycI18n();
            await this.testLanguageDetection();

            console.log('\n' + '='.repeat(50));
            console.log('✅ i18n 多语言测试完成！');
        } catch (error) {
            console.log('\n❌ 测试过程中发生错误:', error);
        }
    }
}

// 如果直接运行此文件，执行测试
if (typeof window === 'undefined') {
    // Node.js环境
    const tester = new I18nTester(BASE_URL);
    tester.runAllTests().catch(console.error);
} else {
    // 浏览器环境
    (window as any).I18nTester = I18nTester;
    console.log('I18nTester class available in window.I18nTester');
    console.log('Run: new I18nTester().runAllTests() to start testing');
}

export { I18nTester };
